package com.uzai.console.web.wxpub;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.ConfigService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.uzai.common.enums.ProductKeyEnum;
import com.uzai.common.enums.SwitchEnum;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.dto.sysplugin.SysPluginIdDto;
import com.uzai.console.dto.wechatprivate.configplan.ConfigPlanIdDto;
import com.uzai.console.dto.wxpubmanage.CreateMaterialDto;
import com.uzai.console.dto.wxpubmanage.DeletePublishDto;
import com.uzai.console.dto.wxpubmanage.QueryMaterialConsoleDto;
import com.uzai.console.dto.wxpubmanage.QueryMaterialDetailDto;
import com.uzai.console.dto.wxpubmanage.QueryMaterialDto;
import com.uzai.console.dto.wxpubmanage.QueryPicMaterialDetailDto;
import com.uzai.console.dto.wxpubmanage.UpdateMaterialDto;
import com.uzai.console.dto.wxpubmanage.UploadMaterialDto;
import com.uzai.console.dto.wxpubmanage.UploadUrlMaterialDto;
import com.uzai.console.dto.wxpubmanage.WxpubAddAuthFreeDto;
import com.uzai.console.dto.wxpubmanage.WxpubMenuDto;
import com.uzai.console.dto.wxpubmanage.WxpubPersonalListDto;
import com.uzai.console.dto.wxpubmanage.WxpubPosterDto;
import com.uzai.console.entity.wxpubmanage.WxpubInfoEntity;
import com.uzai.console.service.configplan.ConfigPlanService;
import com.uzai.console.service.feign.WxServerFeignService;
import com.uzai.console.service.module.ProductAuthService;
import com.uzai.console.service.sysplugin.SysPluginService;
import com.uzai.console.service.wxpubmanage.WxpubInfoService;
import com.uzai.console.vo.module.product.ProductAuthVo;
import com.uzai.console.vo.sysplugin.SysPluginVo;
import com.uzai.console.vo.wechatprivate.configplan.ConfigPlanVo;
import com.uzai.console.vo.wxpub.MaterialBatchGetResponse;
import com.uzai.console.vo.wxpub.MaterialBatchGetResultItem;
import com.uzai.console.vo.wxpub.MediaResponse;
import com.uzai.console.vo.wxpub.NewsItemResponse;
import com.uzai.console.vo.wxpub.PersonalCenterVo;
import com.uzai.console.vo.wxpub.PicByteStringResponse;
import com.uzai.console.vo.wxpub.PlatformModuleVo;
import com.uzai.console.vo.wxpub.WxpubMenuVo;
import com.uzai.console.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.C;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 公众号素材管理
 *
 * @author cen
 * @date 2022/2/27 15:20
 */
@Api(value = "公众号素材管理", tags = "公众号素材管理", hidden = true)
@ApiSort(888)
@RestController
public class WxpubMaterialController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(WxpubMaterialController.class);

    @Autowired
    private WxServerFeignService wxServerFeignService;

    @Autowired
    private WxpubInfoService wxpubInfoService;

    @Autowired
    private ProductAuthService productAuthService;

    @Autowired
    RestTemplate restTemplate ;


    @ApiOperation(value = "创建素材", notes = "创建素材", response = Boolean.class)
    @PostMapping("/wxpub/material/create")
    public Object save(@RequestBody CreateMaterialDto dto) {
        wxServerFeignService.createMaterial(dto);
        return true;
    }

    @ApiOperation(value = "删除图文素材", notes = "删除图文素材", response = Boolean.class)
    @PostMapping("/wxpub/material/delete")
    public Object delete(@RequestBody UpdateMaterialDto dto) {

        if(CollectionUtils.isNotEmpty(dto.getMaterialIdList())) {

            dto.getMaterialIdList().stream().forEach( a-> {
                DeletePublishDto publishDto = new DeletePublishDto();
                publishDto.setMaterialId(a);
                publishDto.setWxpubId(dto.getWxpubId());
                publishDto.setMerId(dto.getMerId());
                wxServerFeignService.deleteMaterial(publishDto);
            });


        }

        return true;
    }


//    @ApiOperation(value = "修改图文素材", notes = "修改图文素材", response = Boolean.class)
//    @PostMapping("/wxpub/material/update")
//    public Object update(@RequestBody UpdateMaterialDto dto) {
//        wxServerFeignService.updateMaterial(dto);
//        return true;
//    }

    @ApiOperation(value = "素材列表查询", notes = "素材列表查询", response = MaterialBatchGetResultItem.class)
    @PostMapping("/wxpub/material/query")
    public Object query(@RequestBody QueryMaterialConsoleDto dto) {
        QueryMaterialDto materialDto = JSONObject.parseObject(JSONObject.toJSONString(dto), QueryMaterialDto.class);
        materialDto.setPageNo((dto.getCurrent() - 1) * dto.getSize());
        materialDto.setPageSize(dto.getSize());
        materialDto.setType("news");
        UzaiRespVo<MaterialBatchGetResponse> respVo = wxServerFeignService.queryMaterial(materialDto);

        Page<MaterialBatchGetResultItem> page = new Page<>();

        page.setTotal(0);
        page.setCurrent(dto.getCurrent());
        page.setSize(0);

        if(respVo != null && respVo.getData() != null && respVo.getCode()== ResponseCode.SUCCESS) {
            page.setRecords(respVo.getData().getItem());
            page.setTotal(respVo.getData().getTotalCount());
            page.setCurrent(dto.getCurrent());
            page.setSize(respVo.getData().getItemCount());
        }

        return page;
    }

    @ApiOperation(value = "素材图文详情查询", notes = "素材详情查询", response = NewsItemResponse.class)
    @PostMapping("/wxpub/material/queryDetail")
    public Object queryDetail(@RequestBody QueryMaterialDetailDto dto) {
        QueryMaterialDto materialDto = JSONObject.parseObject(JSONObject.toJSONString(dto), QueryMaterialDto.class);
        UzaiRespVo<NewsItemResponse> respVo = wxServerFeignService.queryDetail(materialDto);
        return respVo != null? respVo.getData() : new NewsItemResponse();
    }


    @ApiOperation(value = "素材图片详情查询", notes = "素材图片详情查询", response = PicByteStringResponse.class)
    @PostMapping("/wxpub/material/queryPicDetail")
    public Object queryPicDetail(@RequestBody QueryPicMaterialDetailDto dto) {
        QueryMaterialDto materialDto = JSONObject.parseObject(JSONObject.toJSONString(dto), QueryMaterialDto.class);
        materialDto.setMaterialId(dto.getMediaId());
        UzaiRespVo<PicByteStringResponse> respVo = wxServerFeignService.queryPicDetail(materialDto);
        return respVo.getData();
    }



    @ApiOperation(value = "通过url链接上传图片素材", notes = "通过url链接上传图片素材", response = PicByteStringResponse.class)
    @PostMapping("/wxpub/material/urlPicUpload")
    public Object queryPicDetail(@RequestBody UploadUrlMaterialDto materialDto) {

        UzaiRespVo<MediaResponse> respVo = new UzaiRespVo<>();

        try {
            UploadMaterialDto dto = new UploadMaterialDto();
            dto.setWxpubId(materialDto.getWxpubId());
            dto.setUrl(materialDto.getUrl());
            dto.setMerId(getLoginInfo().getMerId());
            respVo = wxServerFeignService.uploadFile(dto);

        }catch (Exception e ) {
            logger.error("err : {}" , e);
        }
        return respVo != null ? respVo.getData() : new MediaResponse();
    }

    @ApiOperation(value = "上传素材", notes = "上传素材", response = MaterialBatchGetResponse.class)
    @PostMapping("/wxpub/material/uploadFile")
    public Object uploadFile(@RequestParam("file") MultipartFile file,
                             @RequestParam("wxpubId") Long wxpubId) {

        UzaiRespVo<MediaResponse> respVo = new UzaiRespVo<>();
        try {
            byte[] bytes = file.getBytes();
            String fileByteString = new String(bytes, "UTF-8");
            UploadMaterialDto dto = new UploadMaterialDto();
            dto.setFileByteString(fileByteString);
            dto.setWxpubId(wxpubId);
            dto.setFileName(file.getOriginalFilename());
            dto.setFileSize(file.getSize());
            dto.setMerId(getLoginInfo().getMerId());
            respVo = wxServerFeignService.uploadFile(dto);
        }catch (Exception e ) {
            logger.error("upload file err : {}" , e);
        }


        return respVo.getData();
    }

    @ApiOperation(value = "查询 平台模块列表", notes = "查询 平台模块列表", response = PlatformModuleVo.class)
    @PostMapping("/wxpub/material/platformModule/list")
    public Object platformModuleList(@RequestBody WxpubPersonalListDto dto) {
        /**
         * 外卖集合页
         * 	美团 	小程序/H5
         * 	饿了么 	小程序/H5/淘口令中间页
         * 	京东
         * 	唯品会
         * 	拼多多	小程序/H5
         */

        List list = new ArrayList();
        list.add(new PersonalCenterVo(6, "外卖集合页", "http://mp1.uzaisoft.com/wx/cms/redirect?cmsType=6&wxpubId="+dto.getWxpubId()));
        list.add(new PersonalCenterVo(7, "美团", "http://mp1.uzaisoft.com/wx/cms/redirect?cmsType=7&wxpubId="+dto.getWxpubId()));
        list.add(new PersonalCenterVo(8, "饿了么", "http://mp1.uzaisoft.com/wx/cms/redirect?cmsType=8&wxpubId="+dto.getWxpubId()));

        List<ProductAuthVo> proAuthList = productAuthService.findProAuthList(dto.getMerId());

        proAuthList.stream().forEach( a -> {
            if( a.getStatus() == SwitchEnum.ON_VALUE) {
                if(StringUtils.equals(ProductKeyEnum.JD.getValue(),a.getCode())) {
                    list.add(new PersonalCenterVo(9, "京东", "http://mp1.uzaisoft.com/wx/cms/redirect?cmsType=9&wxpubId="+dto.getWxpubId()));
                }else if(StringUtils.equals(ProductKeyEnum.VPH.getValue(),a.getCode())) {
                    list.add(new PersonalCenterVo(10, "唯品会", "http://mp1.uzaisoft.com/wx/cms/redirect?cmsType=10&wxpubId="+dto.getWxpubId()));
                }else if(StringUtils.equals(ProductKeyEnum.PDD.getValue(),a.getCode())) {
                    list.add(new PersonalCenterVo(11, "拼多多", "http://mp1.uzaisoft.com/wx/cms/redirect?cmsType=11&wxpubId="+dto.getWxpubId()));
                }
            }
        });

        //list.add(new PersonalCenterVo(12, "活码", "http://mp1.uzaisoft.com/wx/cms/redirect?cmsType=12&wxpubId="+dto.getWxpubId()));

        return list;
    }

    @ApiOperation(value = "查询 个人中心链接列表", notes = "查询 个人中心链接列表", response = PersonalCenterVo.class)
    @PostMapping("/wxpub/material/personalCenter/list")
    public Object personalCenterList(@RequestBody WxpubPersonalListDto dto) {
        List list = new ArrayList();

        list.add(new PersonalCenterVo(1, "自动转链", "http://mp1.uzaisoft.com/wx/cms/redirect?cmsType=1&wxpubId="+dto.getWxpubId()));
        list.add(new PersonalCenterVo(2, "搜索页面", "http://mp1.uzaisoft.com/wx/cms/redirect?cmsType=2&wxpubId="+dto.getWxpubId()));
        list.add(new PersonalCenterVo(3, "个人中心", "http://mp1.uzaisoft.com/wx/cms/redirect?cmsType=3&wxpubId="+dto.getWxpubId()));
        list.add(new PersonalCenterVo(4, "cms首页", "http://mp1.uzaisoft.com/wx/cms/redirect?cmsType=4&wxpubId="+dto.getWxpubId()));
        list.add(new PersonalCenterVo(5, "订单列表", "http://mp1.uzaisoft.com/wx/cms/redirect?cmsType=5&wxpubId="+dto.getWxpubId()));

        return list;
    }

    @ApiOperation(value = "查询公众号菜单配置信息", notes = "查询公众号菜单配置信息", response = WxpubMenuVo.class)
    @PostMapping("/wxpub/menu/query")
    public Object menuQuery(@RequestBody WxpubAddAuthFreeDto wxpubIdDto) {
        return wxpubInfoService.menuQuery(wxpubIdDto);
    }

    @ApiOperation(value = "修改公众号菜单配置信息", notes = "修改公众号菜单配置信息", response = Boolean.class)
    @PostMapping("/wxpub/menu/update")
    public Object menuUpdate(@RequestBody WxpubMenuDto wxpubMenuDto) {
        wxpubInfoService.menuUpdate(wxpubMenuDto);
        return true;
    }

    @ApiOperation(value = "修改公众号海报配置信息", notes = "修改公众号海报配置信息", response = Boolean.class)
    @PostMapping("/wxpub/poster/update")
    public Object menuUpdate(@RequestBody WxpubPosterDto wxpubPosterDto) {
        wxpubInfoService.posterUpdate(wxpubPosterDto);
        return true;
    }


}
